{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c39d4558-7f2e-427f-a731-4a9ffadedad2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2, glob, shutil\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "bffa1ada-8295-49b6-85d5-8ee1cebbee75",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "paths = glob.glob('./train/images/*')\n",
    "paths.sort()\n",
    "\n",
    "lables = glob.glob('./train/labels/*')\n",
    "lables.sort()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "673a110e-7ab7-4452-9cf8-e3ed58f9fa14",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "925"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(paths)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "9e3988e3-6fae-4143-a797-8c4bb446eaca",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'./train/images/000001.jpg'"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "paths[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "9c514b1f-2f40-4357-9f30-f7e1bdf29456",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x7f79feda5fa0>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "img = cv2.imread(paths[0])\n",
    "plt.imshow(img[136:189, 169:193])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "5c82dad3-46a3-4af8-9401-9f87c5e54fa2",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x7f788c201790>"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "img = cv2.imread(paths[0])\n",
    "plt.imshow(img)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "02d51704-ecdd-4e54-839f-9dc5596a8488",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ship 169 136 193 189\\n']"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "open(lables[0]).readlines()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "702af39b-38ad-4f44-8100-e9434a463959",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!\\rm -rf yolo-dataset runs\n",
    "!mkdir yolo-dataset\n",
    "\n",
    "!mkdir yolo-dataset/images\n",
    "!mkdir yolo-dataset/images/train\n",
    "!mkdir yolo-dataset/images/val\n",
    "\n",
    "!mkdir yolo-dataset/labels\n",
    "!mkdir yolo-dataset/labels/train\n",
    "!mkdir yolo-dataset/labels/val"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "62379195-efdd-4465-865f-b7dd3b68efd9",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "def convert(size, box):\n",
    "    dw = 1./(size[0])\n",
    "    dh = 1./(size[1])\n",
    "    x = (box[0] + box[2])/2.0 - 1\n",
    "    y = (box[1] + box[3])/2.0 - 1\n",
    "    w = box[2] - box[0]\n",
    "    h = box[3] - box[1]\n",
    "    x = x*dw\n",
    "    w = w*dw\n",
    "    y = y*dh\n",
    "    h = h*dh\n",
    "    return (x,y,w,h)\n",
    "\n",
    "for path, label in zip(paths[:-100], lables[:-100]):\n",
    "    size = cv2.imread(path).shape\n",
    "    size = [size[1], size[0]]\n",
    "    with open('./yolo-dataset/labels/train/' + path.split('/')[-1][:-3] + 'txt', 'w') as up:\n",
    "        lines = open(label).readlines()\n",
    "        for line in lines:\n",
    "            line = line.strip()\n",
    "            line = line.split()\n",
    "            \n",
    "            box = [int(line[1]), int(line[2]), int(line[3]), int(line[4])]\n",
    "            box = convert(size, box)\n",
    "            up.write('0 ' + \" \".join([str(a) for a in box]) + '\\n')\n",
    "    \n",
    "    shutil.copy(path, './yolo-dataset/images/train/')\n",
    "    \n",
    "for path, label in zip(paths[-100:], lables[-100:]):\n",
    "    size = cv2.imread(path).shape\n",
    "    size = [size[1], size[0]]\n",
    "    with open('./yolo-dataset/labels/val/' + path.split('/')[-1][:-3] + 'txt', 'w') as up:\n",
    "        lines = open(label).readlines()\n",
    "        for line in lines:\n",
    "            line = line.strip()\n",
    "            line = line.split()\n",
    "            \n",
    "            box = [int(line[1]), int(line[2]), int(line[3]), int(line[4])]\n",
    "            box = convert(size, box)\n",
    "            up.write('0 ' + \" \".join([str(a) for a in box]) + '\\n')\n",
    "    \n",
    "    shutil.copy(path, './yolo-dataset/images/val/')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1f89571c-77e1-4559-940d-675c20765b22",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "New https://pypi.org/project/ultralytics/8.0.149 available 😃 Update with 'pip install -U ultralytics'\n",
      "Ultralytics YOLOv8.0.112 🚀 Python-3.9.10 torch-1.12.1+cu113 CUDA:0 (NVIDIA GeForce GTX 1080 Ti, 11178MiB)\n",
      "WARNING ⚠️ Upgrade to torch>=2.0.0 for deterministic training.\n",
      "\u001b[34m\u001b[1myolo/engine/trainer: \u001b[0mtask=detect, mode=train, model=./yolov8m.pt, data=./yolo-dataset.yaml, epochs=20, patience=50, batch=8, imgsz=640, save=True, save_period=-1, cache=False, device=None, workers=8, project=None, name=None, exist_ok=False, pretrained=False, optimizer=SGD, verbose=True, seed=0, deterministic=True, single_cls=False, rect=False, cos_lr=False, close_mosaic=0, resume=False, amp=True, fraction=1.0, profile=False, overlap_mask=True, mask_ratio=4, dropout=0.0, val=True, split=val, save_json=False, save_hybrid=False, conf=None, iou=0.7, max_det=300, half=False, dnn=False, plots=True, source=None, show=False, save_txt=False, save_conf=False, save_crop=False, show_labels=True, show_conf=True, vid_stride=1, line_width=None, visualize=False, augment=False, agnostic_nms=False, classes=None, retina_masks=False, boxes=True, format=torchscript, keras=False, optimize=False, int8=False, dynamic=False, simplify=False, opset=None, workspace=4, nms=False, lr0=0.01, lrf=0.01, momentum=0.937, weight_decay=0.0005, warmup_epochs=3.0, warmup_momentum=0.8, warmup_bias_lr=0.1, box=7.5, cls=0.5, dfl=1.5, pose=12.0, kobj=1.0, label_smoothing=0.0, nbs=64, hsv_h=0.015, hsv_s=0.7, hsv_v=0.4, degrees=0.0, translate=0.1, scale=0.5, shear=0.0, perspective=0.0, flipud=0.0, fliplr=0.5, mosaic=1.0, mixup=0.0, copy_paste=0.0, cfg=None, v5loader=False, tracker=botsort.yaml, save_dir=runs/detect/train\n",
      "Overriding model.yaml nc=80 with nc=1\n",
      "\n",
      "                   from  n    params  module                                       arguments                     \n",
      "  0                  -1  1      1392  ultralytics.nn.modules.conv.Conv             [3, 48, 3, 2]                 \n",
      "  1                  -1  1     41664  ultralytics.nn.modules.conv.Conv             [48, 96, 3, 2]                \n",
      "  2                  -1  2    111360  ultralytics.nn.modules.block.C2f             [96, 96, 2, True]             \n",
      "  3                  -1  1    166272  ultralytics.nn.modules.conv.Conv             [96, 192, 3, 2]               \n",
      "  4                  -1  4    813312  ultralytics.nn.modules.block.C2f             [192, 192, 4, True]           \n",
      "  5                  -1  1    664320  ultralytics.nn.modules.conv.Conv             [192, 384, 3, 2]              \n",
      "  6                  -1  4   3248640  ultralytics.nn.modules.block.C2f             [384, 384, 4, True]           \n",
      "  7                  -1  1   1991808  ultralytics.nn.modules.conv.Conv             [384, 576, 3, 2]              \n",
      "  8                  -1  2   3985920  ultralytics.nn.modules.block.C2f             [576, 576, 2, True]           \n",
      "  9                  -1  1    831168  ultralytics.nn.modules.block.SPPF            [576, 576, 5]                 \n",
      " 10                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \n",
      " 11             [-1, 6]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
      " 12                  -1  2   1993728  ultralytics.nn.modules.block.C2f             [960, 384, 2]                 \n",
      " 13                  -1  1         0  torch.nn.modules.upsampling.Upsample         [None, 2, 'nearest']          \n",
      " 14             [-1, 4]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
      " 15                  -1  2    517632  ultralytics.nn.modules.block.C2f             [576, 192, 2]                 \n",
      " 16                  -1  1    332160  ultralytics.nn.modules.conv.Conv             [192, 192, 3, 2]              \n",
      " 17            [-1, 12]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
      " 18                  -1  2   1846272  ultralytics.nn.modules.block.C2f             [576, 384, 2]                 \n",
      " 19                  -1  1   1327872  ultralytics.nn.modules.conv.Conv             [384, 384, 3, 2]              \n",
      " 20             [-1, 9]  1         0  ultralytics.nn.modules.conv.Concat           [1]                           \n",
      " 21                  -1  2   4207104  ultralytics.nn.modules.block.C2f             [960, 576, 2]                 \n",
      " 22        [15, 18, 21]  1   3776275  ultralytics.nn.modules.head.Detect           [1, [192, 384, 576]]          \n",
      "Model summary: 295 layers, 25856899 parameters, 25856883 gradients, 79.1 GFLOPs\n",
      "\n",
      "Transferred 469/475 items from pretrained weights\n",
      "\u001b[34m\u001b[1mTensorBoard: \u001b[0mStart with 'tensorboard --logdir runs/detect/train', view at http://localhost:6006/\n",
      "\u001b[34m\u001b[1mAMP: \u001b[0mrunning Automatic Mixed Precision (AMP) checks with YOLOv8n...\n",
      "\u001b[34m\u001b[1mAMP: \u001b[0mchecks passed ✅\n",
      "\u001b[34m\u001b[1moptimizer:\u001b[0m SGD(lr=0.01) with parameter groups 77 weight(decay=0.0), 84 weight(decay=0.0005), 83 bias\n",
      "\u001b[34m\u001b[1mtrain: \u001b[0mScanning /home/lyz/work/kaggle/科大讯飞2023/遥感图像倾斜舰船小目标检测挑战赛/yolo-dataset/labels/train... 825 images, 0 backgrounds, 0 corrupt: 100%|██████████| 825/825 [00:00<00:00, 1992.11it/s]\n",
      "\u001b[34m\u001b[1mtrain: \u001b[0mNew cache created: /home/lyz/work/kaggle/科大讯飞2023/遥感图像倾斜舰船小目标检测挑战赛/yolo-dataset/labels/train.cache\n",
      "\u001b[34m\u001b[1malbumentations: \u001b[0mBlur(p=0.01, blur_limit=(3, 7)), MedianBlur(p=0.01, blur_limit=(3, 7)), ToGray(p=0.01), CLAHE(p=0.01, clip_limit=(1, 4.0), tile_grid_size=(8, 8))\n",
      "\u001b[34m\u001b[1mval: \u001b[0mScanning /home/lyz/work/kaggle/科大讯飞2023/遥感图像倾斜舰船小目标检测挑战赛/yolo-dataset/labels/val... 100 images, 0 backgrounds, 0 corrupt: 100%|██████████| 100/100 [00:00<00:00, 1608.04it/s]\n",
      "\u001b[34m\u001b[1mval: \u001b[0mNew cache created: /home/lyz/work/kaggle/科大讯飞2023/遥感图像倾斜舰船小目标检测挑战赛/yolo-dataset/labels/val.cache\n",
      "Plotting labels to runs/detect/train/labels.jpg... \n",
      "Image sizes 640 train, 640 val\n",
      "Using 6 dataloader workers\n",
      "Logging results to \u001b[1mruns/detect/train\u001b[0m\n",
      "Starting training for 20 epochs...\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       1/20      7.25G      1.726      1.868      1.277          3        640: 100%|██████████| 104/104 [00:39<00:00,  2.62it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.54it/s]\n",
      "                   all        100        220      0.797      0.827      0.861      0.467\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       2/20      7.47G      1.438      1.044      1.115         10        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.53it/s]\n",
      "                   all        100        220      0.851      0.856      0.886       0.51\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       3/20      7.46G      1.453      1.018      1.117          7        640: 100%|██████████| 104/104 [00:38<00:00,  2.67it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.60it/s]\n",
      "                   all        100        220      0.904       0.81      0.898      0.537\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       4/20      7.46G      1.431      1.016      1.127          1        640: 100%|██████████| 104/104 [00:38<00:00,  2.68it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.59it/s]\n",
      "                   all        100        220      0.843      0.891      0.904      0.537\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       5/20      7.46G      1.454     0.9385      1.113          2        640: 100%|██████████| 104/104 [00:38<00:00,  2.67it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.57it/s]\n",
      "                   all        100        220      0.905      0.868      0.913      0.495\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       6/20      7.46G      1.377     0.8307      1.103          1        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.57it/s]\n",
      "                   all        100        220      0.912      0.895      0.946      0.577\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       7/20      7.47G      1.355     0.8185      1.082          4        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.61it/s]\n",
      "                   all        100        220      0.965      0.886      0.953      0.593\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       8/20      7.47G      1.325     0.7901      1.086          2        640: 100%|██████████| 104/104 [00:39<00:00,  2.65it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.58it/s]\n",
      "                   all        100        220      0.906      0.905      0.941      0.554\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "       9/20      7.45G      1.314     0.7722      1.077          1        640: 100%|██████████| 104/104 [00:39<00:00,  2.64it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.59it/s]\n",
      "                   all        100        220      0.921      0.901      0.945      0.596\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      10/20      7.47G      1.291      0.753      1.061          1        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.56it/s]\n",
      "                   all        100        220       0.93      0.873      0.934      0.535\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      11/20      7.45G      1.246     0.7171       1.05          2        640: 100%|██████████| 104/104 [00:39<00:00,  2.65it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.64it/s]\n",
      "                   all        100        220      0.936      0.909       0.96      0.616\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      12/20      7.45G      1.272     0.7132      1.044          2        640: 100%|██████████| 104/104 [00:39<00:00,  2.65it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.58it/s]\n",
      "                   all        100        220      0.923      0.922      0.957      0.646\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      13/20      7.47G      1.231     0.7087      1.031          1        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.60it/s]\n",
      "                   all        100        220       0.94      0.924      0.954      0.627\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      14/20      7.45G      1.174     0.6577      1.024          2        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.60it/s]\n",
      "                   all        100        220      0.961      0.918      0.977      0.647\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      15/20      7.45G      1.134     0.6408      1.026          1        640: 100%|██████████| 104/104 [00:39<00:00,  2.65it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.62it/s]\n",
      "                   all        100        220      0.945      0.933      0.974      0.641\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      16/20      7.47G      1.131     0.6205      1.006          3        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.61it/s]\n",
      "                   all        100        220      0.956      0.923      0.973      0.657\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      17/20      7.47G      1.121     0.6109       1.02          3        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.57it/s]\n",
      "                   all        100        220      0.949      0.941       0.98       0.66\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      18/20      7.47G      1.087     0.5742     0.9956          6        640: 100%|██████████| 104/104 [00:39<00:00,  2.62it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.59it/s]\n",
      "                   all        100        220      0.949      0.959      0.982      0.677\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      19/20      7.47G      1.069     0.5677     0.9854          9        640: 100%|██████████| 104/104 [00:39<00:00,  2.66it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:01<00:00,  4.58it/s]\n",
      "                   all        100        220      0.967       0.95      0.983      0.678\n",
      "\n",
      "      Epoch    GPU_mem   box_loss   cls_loss   dfl_loss  Instances       Size\n",
      "      20/20      7.47G      1.035      0.547     0.9727          3        640: 100%|██████████| 104/104 [00:39<00:00,  2.67it/s]\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:02<00:00,  2.41it/s]\n",
      "                   all        100        220      0.981      0.943      0.986      0.695\n",
      "\n",
      "20 epochs completed in 0.244 hours.\n",
      "Optimizer stripped from runs/detect/train/weights/last.pt, 52.0MB\n",
      "Optimizer stripped from runs/detect/train/weights/best.pt, 52.0MB\n",
      "\n",
      "Validating runs/detect/train/weights/best.pt...\n",
      "Ultralytics YOLOv8.0.112 🚀 Python-3.9.10 torch-1.12.1+cu113 CUDA:0 (NVIDIA GeForce GTX 1080 Ti, 11178MiB)\n",
      "Model summary (fused): 218 layers, 25840339 parameters, 0 gradients, 78.7 GFLOPs\n",
      "                 Class     Images  Instances      Box(P          R      mAP50  mAP50-95): 100%|██████████| 7/7 [00:02<00:00,  2.36it/s]\n",
      "                   all        100        220      0.981      0.942      0.986      0.695\n",
      "Speed: 0.3ms preprocess, 12.3ms inference, 0.0ms loss, 0.7ms postprocess per image\n",
      "Results saved to \u001b[1mruns/detect/train\u001b[0m\n"
     ]
    }
   ],
   "source": [
    "from ultralytics import YOLO\n",
    "\n",
    "model = YOLO(\"./yolov8m.pt\")\n",
    "results = model.train(data=\"./yolo-dataset.yaml\", epochs=20, batch=8)  # 训练模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "a82b014c-7bcd-4b1a-bc04-b0493a9d4263",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n",
      "image 1/1 /home/lyz/work/kaggle/科大讯飞2023/遥感图像倾斜舰船小目标检测挑战赛/train/images/000007.jpg: 480x640 1 ship, 13.5ms\n",
      "Speed: 1.5ms preprocess, 13.5ms inference, 1.1ms postprocess per image at shape (1, 3, 640, 640)\n"
     ]
    }
   ],
   "source": [
    "from ultralytics import YOLO\n",
    "import glob\n",
    "model = YOLO(\"runs/detect/train/weights/best.pt\")\n",
    "\n",
    "predictions = model.predict('./train/images/000007.jpg', imgsz=640)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "id": "0709d87a-efed-4a3f-ba38-2fa73b48b913",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "for prediction in predictions[0].boxes.data:\n",
    "    break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "id": "ac3bd7cc-eee6-4650-868d-f135a3475afc",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "tensor([[204.3412, 268.2345, 219.6001, 310.5176,   0.8076,   0.0000]], device='cuda:0')"
      ]
     },
     "execution_count": 37,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "predictions[0].boxes.data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "12d06058-f9df-4c4e-90be-0adf90c7d5da",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "['ship 204 265 221 312\\n']"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "open('./train/labels/000007.txt').readlines()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "id": "31c0f5b4-00a2-4c90-8088-49a5ae6f6677",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tilting-ship/\n",
      "tilting-ship/best.pt\n",
      "tilting-ship/.ipynb_checkpoints/\n",
      "tilting-ship/.ipynb_checkpoints/run-checkpoint.py\n",
      "tilting-ship/run.py\n"
     ]
    }
   ],
   "source": [
    "!tar -cvzf tilting-ship.tar.gz tilting-ship"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "id": "674286d8-045e-4642-b8c3-b516d9e75581",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "upload: 'tilting-ship.tar.gz' -> 's3://ai-competition/0fs76epw/tilting-ship.tar.gz'  [part 1 of 4, 15MB] [1 of 1]\n",
      " 15728640 of 15728640   100% in   19s   789.31 kB/s  done\n",
      "upload: 'tilting-ship.tar.gz' -> 's3://ai-competition/0fs76epw/tilting-ship.tar.gz'  [part 2 of 4, 15MB] [1 of 1]\n",
      " 15728640 of 15728640   100% in   19s   772.08 kB/s  done\n",
      "upload: 'tilting-ship.tar.gz' -> 's3://ai-competition/0fs76epw/tilting-ship.tar.gz'  [part 3 of 4, 15MB] [1 of 1]\n",
      " 15728640 of 15728640   100% in   20s   752.27 kB/s  done\n",
      "upload: 'tilting-ship.tar.gz' -> 's3://ai-competition/0fs76epw/tilting-ship.tar.gz'  [part 4 of 4, 811kB] [1 of 1]\n",
      " 831323 of 831323   100% in    0s   906.84 kB/s  done\n"
     ]
    }
   ],
   "source": [
    "!s3cmd put tilting-ship.tar.gz s3://ai-competition/0fs76epw/tilting-ship.tar.gz"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2ebb0f21-d6e1-4e05-bda0-bfcaff682c46",
   "metadata": {},
   "source": [
    "- run.py内容\n",
    "\n",
    "```python\n",
    "from ultralytics import YOLO\n",
    "import glob\n",
    "model = YOLO(\"./best.pt\")\n",
    "\n",
    "for path in glob.glob('/work/data/object-detection-for-tilting-ships-test-set/*'):\n",
    "    predictions = model.predict(path, imgsz=640)\n",
    "    with open(\"/work/output/\" + path.split('/')[-1][:-4] + '.txt', 'w') as file:\n",
    "        for idx, prediction in enumerate(predictions[0].boxes.data):\n",
    "            cls = int(predictions[0].boxes.cls[idx].item())\n",
    "            cls = 'ship'\n",
    "            score = predictions[0].boxes.conf[idx].item()\n",
    "            file.write(f\"{cls} {score} {int(prediction[0].item())} {int(prediction[1].item())} {int(prediction[2].item())} {int(prediction[3].item())}\\n\")   \n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f490b1f5-a8d8-45a1-bbcb-44bb04d23e81",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3.10"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
